@extends('layouts.app')

@section('title', '账单详情')

@section('content')
<!-- 页面头部 -->
<div class="page-header">
    @if(request()->headers->get('referer'))
        <button class="back-btn" onclick="history.back()">‹</button>
    @else
        <button class="back-btn" onclick="window.location.href='{{ route('details.index') }}'">‹</button>
    @endif
    <h1 class="page-title">账单详情</h1>
</div>

<!-- 主要内容 -->
<div class="bill-detail-container">
    <!-- 账单信息卡片 -->
    <div class="bill-card">
        <div class="bill-header">
            <div class="bill-category-icon" id="category-icon">{{ $transaction['sub_category']['icon'] ?? '📝' }}</div>
            <div class="bill-info">
                <div class="bill-category" id="bill-category">{{ $transaction['category']['name'] }}</div>
                <div class="bill-subcategory" id="bill-subcategory">{{ $transaction['sub_category']['name'] ?? '' }}</div>
            </div>
            <div class="bill-amount {{ $transaction['type'] === 'expense' ? 'expense' : 'income' }}" id="bill-amount">
                {{ $transaction['type'] === 'expense' ? '-' : '+' }}¥{{ number_format($transaction['amount'], 2) }}
            </div>
        </div>

        <div class="bill-details">
            <div class="bill-detail-item with-avatar">
                <div class="bill-detail-label">记账人</div>
                <div class="bill-detail-value">
                    <div class="item-user-avatar" id="recorder-avatar">
                        @if($transaction['user']->avatar_url)
                            <img src="{{ $transaction['user']->avatar_url }}" alt="{{ $transaction['user']->nickname ?: $transaction['user']->name }}" style="width: 30px; height: 30px; border-radius: 50%; object-fit: cover;">
                        @else
                            {{ strtoupper(substr($transaction['user']->nickname ?: $transaction['user']->name, 0, 1)) }}
                        @endif
                    </div>
                    <span id="bill-recorder">{{ $transaction['user']->nickname ?: $transaction['user']->name }}</span>
                </div>
            </div>
            <div class="bill-detail-item">
                <div class="bill-detail-label">日期</div>
                <div class="bill-detail-value" id="bill-time">
                    @php
                        $transactionDate = new DateTime($transaction['transaction_date']);
                        echo $transactionDate->format('Y-m-d');
                    @endphp
                </div>
            </div>
            <div class="bill-detail-item">
                <div class="bill-detail-label">账本</div>
                <div class="bill-detail-value" id="bill-book">{{ Auth::user()->getCurrentDefaultBook()->name }}</div>
            </div>
            <div class="bill-detail-item">
                <div class="bill-detail-label">记录时间</div>
                <div class="bill-detail-value" id="bill-payment">
                    @php
                        $transactionDate = new DateTime($transaction['created_at']);
                        echo $transactionDate->format('Y-m-d H:i:s');
                    @endphp
                </div>
            </div>
        </div>

        <div class="bill-note">
            <div class="bill-note-title">备注</div>
            <div class="bill-note-content" id="bill-note">{{ $transaction['description'] ?: '' }}</div>
        </div>

        <div class="bill-actions">
            <div class="bill-action-btn btn-edit" id="edit-bill-btn" onclick="window.location.href='/transaction/{{ $transaction['id'] }}/edit'">编辑</div>
            <div class="bill-action-btn btn-delete" id="delete-bill-btn">删除</div>
        </div>
    </div>

    @if($transaction['image'] || $transaction['text'])
        <div class="ai-input-section">
            <div class="section-title">一句话记账</div>

            @if($transaction['text'])
                <!-- AI识别结果 -->
                <div class="ai-input-card">
                    <div class="ai-input-header">
                        <div class="ai-input-icon">🎤</div>
                        <div class="ai-input-title">一句话记账</div>
                    </div>

                    <div class="voice-input-container">
                        <div class="voice-input-text" id="voice-input-text">{{ $transaction['text'] }}</div>
                        @if($transaction['audio'])
                            <div class="voice-input-icon" id="play-audio-btn" onclick="playAudio()" style="cursor: pointer;" title="点击播放语音">🎤</div>
                            <audio id="transaction-audio" style="display: none;">
                                <source src="{{ \Illuminate\Support\Facades\Storage::url($transaction['audio']) }}" type="audio/mpeg">
                                <source src="{{ \Illuminate\Support\Facades\Storage::url($transaction['audio']) }}" type="audio/wav">
                                您的浏览器不支持音频播放。
                            </audio>
                        @endif
                    </div>
                </div>
            @endif

            @if($transaction['image'])
                <!-- 图片上传区域 -->
                <div class="ai-input-card" id="image-recognition-card">
                    <div class="image-container">
                        <div class="bill-image">
                            <img id="receipt-image" src="{{ \Illuminate\Support\Facades\Storage::url($transaction['image']) }}" alt="票据图片">
                        </div>
                    </div>
                </div>
            @endif
        </div>
    @endif
</div>

<!-- 确认删除弹窗 -->
<div class="modal" id="delete-transaction-modal" style="display: none;">
    <div class="modal-content">
        <div class="modal-header">
            <h3>确认删除</h3>
            <button class="modal-close" id="delete-modal-close">&times;</button>
        </div>
        <div class="modal-body">
            <p>确定要删除这条账单记录吗？此操作不可恢复。</p>
            <input type="hidden" id="delete-transaction-id" value="{{ $transaction['id'] }}">
        </div>
        <div class="modal-footer">
            <button class="btn btn-secondary" id="cancel-delete">取消</button>
            <button class="btn btn-danger" id="confirm-delete">删除</button>
        </div>
    </div>
</div>
@endsection

@push('styles')
<style>
    .app-container {
        padding-bottom: 0;
    }

    .bill-detail-container {
        padding: 20px;
    }

    .bill-card {
        background: white;
        border-radius: 12px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        padding: 20px;
        margin-bottom: 20px;
    }

    .bill-header {
        display: flex;
        align-items: center;
        margin-bottom: 20px;
        padding-bottom: 15px;
        border-bottom: 1px solid #f0f0f0;
    }

    .bill-category-icon {
        width: 40px;
        height: 40px;
        background-color: #f0f5ff;
        border-radius: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 20px;
        margin-right: 15px;
    }

    .bill-info {
        flex: 1;
    }

    .bill-category {
        font-size: 16px;
        font-weight: 600;
        color: #333;
    }

    .bill-subcategory {
        font-size: 14px;
        color: #666;
        margin-top: 2px;
    }

    .bill-amount {
        font-size: 18px;
        font-weight: 700;
    }

    .bill-amount.expense {
        color: #e74c3c;
    }

    .bill-amount.income {
        color: #2ecc71;
    }

    .bill-details {
        margin-bottom: 20px;
    }

    .bill-detail-item {
        display: flex;
        justify-content: space-between;
        margin-bottom: 12px;
    }

    .bill-detail-label {
        color: #666;
        font-size: 14px;
    }

    .bill-detail-value {
        color: #333;
        font-size: 14px;
        font-weight: 500;
        text-align: right;
    }

    .bill-note {
        background-color: #f9f9f9;
        border-radius: 8px;
        padding: 12px 15px;
        margin-bottom: 20px;
    }

    .bill-note-title {
        font-size: 14px;
        color: #666;
        margin-bottom: 5px;
    }

    .bill-note-content {
        font-size: 14px;
        color: #333;
    }

    .bill-actions {
        display: flex;
        justify-content: space-between;
    }

    .bill-action-btn {
        flex: 1;
        text-align: center;
        padding: 10px 0;
        border-radius: 8px;
        font-size: 14px;
        font-weight: 500;
        cursor: pointer;
    }

    .btn-edit {
        background-color: #f0f5ff;
        color: #667eea;
        margin-right: 10px;
    }

    .btn-delete {
        background-color: #fff0f0;
        color: #e74c3c;
    }

    .bill-detail-item.with-avatar .bill-detail-value {
        display: flex;
        align-items: center;
    }

    .item-user-avatar {
        width: 30px;
        height: 30px;
        border-radius: 50%;
        background-color: #f0f5ff;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 10px;
        color: white;
        font-weight: bold;
        font-size: 14px;
    }

    .ai-recognition-result {
        background-color: #f9f9f9;
        border-radius: 10px;
        padding: 15px;
    }

    .image-container {
        margin: 15px 0;
    }

    .bill-image {
        width: 100%;
        border-radius: 10px;
        overflow: hidden;
        margin-bottom: 10px;
    }

    .bill-image img {
        width: 100%;
        border-radius: 12px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    .ai-input-section {
        margin-bottom: 60px;
    }

    .section-title {
        font-size: 16px;
        font-weight: 600;
        margin-bottom: 15px;
        color: #333;
    }

    .ai-input-card {
        background: white;
        border-radius: 12px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        padding: 20px;
        margin-bottom: 20px;
    }

    .ai-input-header {
        display: flex;
        align-items: center;
        margin-bottom: 15px;
    }

    .ai-input-icon {
        width: 30px;
        height: 30px;
        background-color: #f0f5ff;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 16px;
        margin-right: 10px;
    }

    .ai-input-title {
        font-size: 15px;
        font-weight: 600;
        color: #333;
    }

    .voice-input-container {
        background-color: #f0f5ff;
        border-radius: 10px;
        padding: 15px;
        display: flex;
        align-items: center;
        margin-bottom: 15px;
    }

    .voice-input-text {
        flex: 1;
        font-size: 14px;
        color: #333;
    }

    .voice-input-icon {
        width: 30px;
        height: 30px;
        background-color: #667eea;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 14px;
        transition: all 0.3s ease;
    }

    .voice-input-icon:hover {
        background-color: #5a67d8;
        transform: scale(1.1);
    }

    .voice-input-icon.playing {
        background-color: #e53e3e;
        animation: pulse 1s infinite;
    }

    @keyframes pulse {
        0% {
            transform: scale(1);
        }
        50% {
            transform: scale(1.1);
        }
        100% {
            transform: scale(1);
        }
    }

    .ai-recognition-result {
        background-color: #f9f9f9;
        border-radius: 10px;
        padding: 15px;
    }
</style>
@endpush

@push('scripts')
<script>
    $(document).ready(function() {
        // 绑定事件
        bindEvents();
    });

    // 绑定事件
    function bindEvents() {
        // 删除按钮点击事件
        document.getElementById('delete-bill-btn').addEventListener('click', function() {
            // 显示确认删除弹窗
            document.getElementById('delete-transaction-modal').style.display = 'block';
        });

        // 关闭删除确认弹窗
        document.getElementById('delete-modal-close').addEventListener('click', function() {
            document.getElementById('delete-transaction-modal').style.display = 'none';
        });

        document.getElementById('cancel-delete').addEventListener('click', function() {
            document.getElementById('delete-transaction-modal').style.display = 'none';
        });

        // 确认删除按钮点击事件
        document.getElementById('confirm-delete').addEventListener('click', function() {
            const transactionId = document.getElementById('delete-transaction-id').value;

            $.ajax({
                url: `/transaction/${transactionId}`,
                method: 'DELETE',
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                success: function(response) {
                    if (response.success) {
                        // 关闭弹窗
                        document.getElementById('delete-transaction-modal').style.display = 'none';

                        // 显示成功消息
                        showSuccess('账单已成功删除');

                        // 返回明细页面
                        setTimeout(() => {
                            window.location.href = '/details';
                        }, 1500);
                    } else {
                        showError(response.message || '删除失败');
                    }
                },
                error: function() {
                    showError('删除失败，请检查网络连接');
                }
            });
        });
    }

    // 显示错误消息
    function showError(message) {
        alert(message);
    }

    // 显示成功消息
    function showSuccess(message) {
        alert(message);
    }

    // 播放音频
    function playAudio() {
        const audio = document.getElementById('transaction-audio');
        const playBtn = document.getElementById('play-audio-btn');

        if (audio) {
            // 防止重复点击
            if (playBtn.disabled) return;

            if (audio.paused) {
                playBtn.disabled = true;
                audio.play().then(() => {
                    playBtn.innerHTML = '⏸️';
                    playBtn.title = '点击暂停';
                    playBtn.classList.add('playing');
                    playBtn.disabled = false;
                }).catch((error) => {
                    console.error('音频播放失败:', error);
                    // 只有在非AbortError时才显示错误信息
                    if (error.name !== 'AbortError') {
                        showError('音频播放失败');
                    }
                    playBtn.disabled = false;
                    // 重置按钮状态
                    playBtn.innerHTML = '🎤';
                    playBtn.title = '点击播放语音';
                    playBtn.classList.remove('playing');
                });
            } else {
                try {
                    audio.pause();
                    playBtn.innerHTML = '🎤';
                    playBtn.title = '点击播放语音';
                    playBtn.classList.remove('playing');
                } catch (error) {
                    console.error('音频暂停失败:', error);
                }
            }

            // 监听音频结束事件（只绑定一次）
            if (!audio.hasEndedListener) {
                audio.addEventListener('ended', function() {
                    playBtn.innerHTML = '🎤';
                    playBtn.title = '点击播放语音';
                    playBtn.classList.remove('playing');
                    playBtn.disabled = false;
                });
                audio.hasEndedListener = true;
            }
        }
    }
</script>
@endpush
